# !/usr/bin/env python
# -*- coding:utf-8 -*-
import requests
import redis
import json
import hashlib

import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
from config import dmp
from config import db

class cityArea(object):
    def __init__(self):
        self.redisClient = redis.StrictRedis(host=db.redis.get("host"), port=db.redis.get("port"), db=db.redis.get("db"), password=db.redis.get("auth"))
        self.cityAreaKey = "cityArea_%s" # 城区
        self.cityArea2Key = "cityArea2_%s" # 商圈

    def update(self, city):
        """
        跟新数据
        :param city:
        :return:
        """
        url = dmp.cityArea % {"city":city}
        report = requests.get(url)

        content = report.content

        resutl = json.loads(content)
        datas = resutl.get('data')

        cityAreaKey = self.cityAreaKey % city
        cityArea2Key = self.cityArea2Key % city
        for data in datas:
            cityAreaData = {"name":data.get("name"), "id": data.get("id")}
            self.redisClient.hset(cityAreaKey, self.md5(data.get("name")), cityAreaData)
            list_cityarea2 = data.get("list_cityarea2")
            for areaName in list_cityarea2:
                cityArea2Data = {"name": areaName, "id": list_cityarea2[areaName]['id'], "pid":data.get("id"), 'pname':data.get("name")}
                self.redisClient.hset(cityArea2Key, self.md5(areaName), cityArea2Data)

        return True

    def md5(self, str):
        m2 = hashlib.md5()  # 获取资源
        m2.update(str)  # 生成MD5
        result = m2.hexdigest()  # 获取MD5
        return result




if __name__ == "__main__":
    cityArea().update("bj")